/**  
 * @Title: JobService.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-06-26 08:30:04 
 */  
package com.fsxgt.datagrid.console.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Service;

/**  
 * @ClassName: JobService
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-06-26 08:30:04 
*/
@Service
public class ScheduledHelper {
	
	private final class ScheduledTask {
		
		private Runnable runnable;
		public ScheduledTask(Runnable runnable) {
			this.runnable=runnable;
		}
		
		public Runnable getRunnable() {
			return this.runnable;
		}
		 
	    public volatile ScheduledFuture<?> future;
	    /**
	     * 取消定时任务
	     */
	    public void cancel() {
	        ScheduledFuture<?> future = this.future;
	        if (future != null) {
	            future.cancel(true);
	        }
	    }
	}
	
	
	@Autowired
	private TaskScheduler taskScheduler;
	private final Map<String, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);

	
	
	private ScheduledTask scheduleCronTask(CronTask cronTask) {
		
        ScheduledTask scheduledTask = new ScheduledTask(cronTask.getRunnable());
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }
	
	/**
     * 新增定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(String taskId,Runnable task, String cronExpression) {
        addCronTask(taskId,new CronTask(task, cronExpression));
    }
    

	private void addCronTask(String taskId,CronTask cronTask) {
        if (cronTask != null) {
            if (this.scheduledTasks.containsKey(taskId)) {
                removeCronTask(taskId);
            }
            this.scheduledTasks.put(taskId, scheduleCronTask(cronTask));
        }
    }
	
	public Map<String,Runnable> getRunnableMap() {
		Map<String,Runnable> map=new HashMap();
		this.scheduledTasks.forEach((k,v)->{
			map.put(k, v.getRunnable());
		});
		return map;
		
	}

	
	
	/**
     * 移除定时任务
     */
    public void removeCronTask(String taskId) {
    	
        ScheduledTask scheduledTask = this.scheduledTasks.remove(taskId);
        if (scheduledTask != null){
            scheduledTask.cancel();
        }
    }
    

    public void clear() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }




}
